package com.mall.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.mall.context.BaseContext;
import com.mall.domain.dto.AddressDTO;
import com.mall.domain.po.Address;
import com.mall.domain.vo.AddressVO;
import com.mall.mapper.AddressMapper;
import com.mall.service.AddressService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 勾新杰
 * @version 1.0
 * @date 2024/11/22 20:52
 */
@Service
@RequiredArgsConstructor
public class AddressServiceImpl implements AddressService {

    private final AddressMapper addressMapper;

    /**
     * 新增地址
     *
     * @param addressDTO 地址传输对象
     */
    @Override
    public void addAddress(AddressDTO addressDTO) {
        // 1、构建地址对象
        Address address = Address.builder()
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .build();
        // 2、复制属性
        BeanUtil.copyProperties(addressDTO, address);
        address.setUserId(BaseContext.getCurrentId());
        // 3、插入数据库
        addressMapper.insert(address);
    }

    /**
     * 查询地址列表
     *
     * @return 地址列表
     */
    @Override
    public List<AddressVO> listAddress() {
        // 1. 获取当前用户id
        Long userId = BaseContext.getCurrentId();
        // 2. 查询地址列表
        List<Address> addressList = addressMapper.getByUserId(userId);
        // 3. 转换为VO返回
        return BeanUtil.copyToList(addressList, AddressVO.class);
    }

    /**
     * 查询某个地址详情
     *
     * @param id 地址id
     * @return 地址详情
     */
    @Override
    public AddressVO getAddressById(Long id) {
        return addressMapper.getByIdAndUserId(id, BaseContext.getCurrentId());
    }

    /**
     * 修改地址
     *
     * @param addressDTO 地址传输对象
     * @param id         地址id
     */
    @Override
    public void updateAddress(AddressDTO addressDTO, Long id) {
        // 1. 构建地址对象
        Address address = Address.builder()
                .id(id)
                .updateTime(LocalDateTime.now())
                .build();
        // 2. 复制属性
        BeanUtil.copyProperties(addressDTO, address);
        // 3. 更新数据库
        addressMapper.update(address);
    }

    /**
     * 删除地址
     *
     * @param id 地址id
     */
    @Override
    public void deleteAddress(Long id) {
        addressMapper.deleteById(id);
    }
}
